import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import { Card, Spin, Badge, Button, Row, Divider, Modal, Table } from 'antd';
import StandardTable from '@/components/StandardTable';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TextOverFlow from '../../components/TextOverFlow';

const { Description } = DescriptionList;

@connect(({ replacetask, loading }) => ({
  loading: loading.models.replacetask,
  replTask: replacetask.replTask,
  replReqs: replacetask.replReqs,
  pageTaskData: replacetask.pageTaskData,
  pagePersonData: replacetask.pagePersonData,
  perDetailInfo: replacetask.perDetailInfo,
}))
class Detail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: null,
      replTaskId: null,
      corpId: null,
      execBizType: null,
      visible: false,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { replTaskId } = queryString.parse(location.search);
    const { activeKey } = queryString.parse(location.search);
    this.setState({ activeKey, replTaskId });
    // 获取替数任务详情信息
    dispatch({
      type: 'replacetask/fetchDetail',
      payload: { replTaskId },
    });
  }

  // 关闭人员明细弹窗
  handleOk = () => {
    this.setState({
      visible: false,
    });
  };

  // 打开人员明细弹框
  goDetail = record => {
    const { dispatch } = this.props;
    const { replTaskId } = this.state;
    const pageArg = {
      currentPage: 1,
      pageSize: 10,
    };
    this.setState({
      visible: true,
      corpId: record.corpId,
      execBizType: record.execBizType,
    });
    dispatch({
      type: 'replacetask/fetchPersonList',
      payload: {
        replTaskId,
        corpId: record.corpId,
        execBizType: record.execBizType,
        pageArg,
      },
    });
  };

  // 人员明细表格有变化：比如：切换页码
  handlePersonDetailChange = pagination => {
    const { replTaskId, corpId, execBizType } = this.state;
    const { dispatch } = this.props;
    const pageArg = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    dispatch({
      type: 'replacetask/fetchPersonList',
      payload: {
        replTaskId,
        corpId,
        execBizType,
        pageArg,
      },
    });
  };

  render() {
    const { loading, replTask, replReqs, pageTaskData, pagePersonData, perDetailInfo } = this.props;
    const { activeKey, visible } = this.state;
    // 替数明细表格
    const columns = [
      {
        title: '涉及供应商',
        dataIndex: 'suppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '涉及订单明细范围',
        dataIndex: 'execBizTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '替数项',
        dataIndex: 'taskTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '涉及人数',
        dataIndex: 'counts',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text === 0 ? 0 : (text && text) || '--'),
      },
      {
        title: activeKey === '3' || activeKey === '4' ? '替数状态' : null,
        dataIndex: 'taskStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => {
          if (activeKey === '3' || activeKey === '4') {
            // 1 已创建 2 执行中  3 已执行
            const taskState = ['warning', 'default', 'processing', 'success'];
            return <Badge status={taskState[record.taskState]} text={record.taskStateName} />;
          }
        },
      },
      {
        title: activeKey === '3' || activeKey === '4' ? '失败人数' : null,
        dataIndex: 'failCounts',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => {
          if (activeKey === '3' || activeKey === '4') {
            return text === 0 ? 0 : (text && text) || '--';
          }
        },
      },
      {
        title: activeKey === '1' ? '生成结果' : null,
        dataIndex: 'taskStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => {
          if (activeKey === '1') {
            // 1 已创建 2 执行中  3 已执行
            const taskState = ['warning', 'default', 'processing', 'success'];
            return <Badge status={taskState[record.taskState]} text={record.taskStateName} />;
          }
        },
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.goDetail(record)}>查看</a>
          </span>
        ),
      },
    ];
    // 人员明细表格
    const personDetailColumns = [
      {
        title: '员工姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '证件号',
        dataIndex: 'certNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '签约方名称',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '生效年月',
        dataIndex: 'startDate',
        onCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        onHeaderCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        render: text => (text && `${`${text}`.substring(0, 4)}-${`${text}`.substring(4)}`) || '--',
      },
      {
        title: '结束年月',
        dataIndex: 'stopDate',
        onCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        onHeaderCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        render: text => (text && `${`${text}`.substring(0, 4)}-${`${text}`.substring(4)}`) || '--',
      },
      {
        title: '替数项',
        dataIndex: 'taskTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '替数前值',
        dataIndex: 'valOld',
        onCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        onHeaderCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '替数后值',
        dataIndex: 'valNew',
        onCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        onHeaderCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        render: text => (text && text) || '--',
      },
      {
        title: activeKey === '3' || activeKey === '4' ? '替数结果' : null,
        dataIndex: 'taskResultName',
        onCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        onHeaderCell: () => ({ style: { textAlign: 'center', width: '90px' } }),
        render: (text, record) => {
          if (activeKey === '3' || activeKey === '4') {
            const taskResult = ['processing', 'success', 'error'];
            return (
              <Badge
                status={record.taskResult ? taskResult[record.taskResult] : taskResult[0]}
                text={record.taskResultName || '--'}
              />
            );
          }
        },
      },
      {
        title: activeKey === '3' || activeKey === '4' ? '失败原因' : null,
        dataIndex: 'errorInfo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => {
          if (activeKey === '3' || activeKey === '4') {
            return <TextOverFlow text={text} />
          }
        },
      },
    ];
    return (
      <PageHeaderWrapper>
        <Spin tip="loading..." spinning={loading}>
          <Card title={<span style={{ fontWeight: 'bolder' }}>替数任务详情</span>}>
            <DescriptionList style={{ marginBottom: 24 }}>
              <Description term="替数任务类型">{replTask.taskTypeName || '--'}</Description>
              <Description term="关联请求数量">{replTask.reqNum || '--'}</Description>
              {activeKey === '3' || activeKey === '4' ? (
                <Description term="替数开始时间">
                  {moment(replTask.creTime).format('YYYY-MM-DD HH:mm') || '--'}
                </Description>
              ) : null}
              {activeKey === '4' ? (
                <Description term="替数结束时间">
                  {moment(replTask.execBeginTime).format('YYYY-MM-DD HH:mm') || '--'}
                </Description>
              ) : null}
              <Description term="任务创建时间">
                {moment(replTask.creTime).format('YYYY-MM-DD HH:mm') || '--'}
              </Description>
            </DescriptionList>
            <Row style={{ border: '1px solid #e8e8e8' }}>
              <h4
                style={{
                  fontWeight: 'bolder',
                  background: '#fafafa',
                  lineHeight: '40px',
                  paddingLeft: 20,
                  width: '100%',
                }}
              >
                涉及替数请求
              </h4>
              {replReqs?.map(item => (
                <Card style={{ width: '100%' }}>
                  <DescriptionList>
                    <Description term="替数请求">{item.replReqName || '--'}</Description>
                    <Description term="修改内容">{item.chgContentName || '--'}</Description>
                    <Description term="生效年月">
                      {(item.startDate &&
                        `${`${item.startDate}`.substring(0, 4)}-${`${item.startDate}`.substring(
                          4
                        )}`) ||
                        '--'}
                    </Description>
                    <Description term="结束年月">
                      {(item.stopDate &&
                        `${`${item.stopDate}`.substring(0, 4)}-${`${item.stopDate}`.substring(
                          4
                        )}`) ||
                        '--'}
                    </Description>
                    <Description term="差额账单处理方式">{item.diffHdlWayName || '--'}</Description>
                    <Description term="请求添加人">{item.reqAddName || '--'}</Description>
                    <Description term="请求供应商">{item.reqSuppName || '--'}</Description>
                    <Description term="请求添加时间">
                      {moment(item.creTime).format('YYYY-MM-DD HH:mm') || '--'}
                    </Description>
                  </DescriptionList>
                  <Divider />
                </Card>
              ))}
            </Row>
          </Card>
          <Card title={<span style={{ fontWeight: 'bolder' }}>替数明细</span>}>
            <Table
              dataSource={pageTaskData || []}
              columns={columns}
              pagination={false}
              rowSelection={null}
              selectedRows={[]}
              selectedRowKeys={[]}
            />
          </Card>
          {/* 人员明细弹框 */}
          {visible && (
            <Modal
              width="1200px"
              visible={visible}
              onCancel={this.handleOk}
              title={
                <div style={{ marginRight: 15 }}>
                  <span style={{ marginRight: 12, fontSize: 16, fontWeight: 'bold' }}>
                    人员明细
                  </span>
                  {perDetailInfo && (
                    <span style={{ fontSize: 12 }}>{`（${perDetailInfo}）` || ''}</span>
                  )}
                </div>
              }
              footer={[
                <Button key="submit" type="primary" onClick={this.handleOk}>
                  关闭
                </Button>,
              ]}
            >
              <Card>
                <StandardTable
                  rowSelection={null}
                  selectedRows={[]}
                  selectedRowKeys={[]}
                  loading={loading}
                  data={pagePersonData}
                  columns={personDetailColumns}
                  onChange={this.handlePersonDetailChange}
                />
              </Card>
            </Modal>
          )}
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={() => router.goBack()}> 返回</Button>
          </FooterToolbar>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Detail;
